﻿using System.Collections.Generic;
using System.Linq;
using Apps.Web.Core;
using Apps.IBLL.PUB;
using Apps.Locale;
using System.Web.Mvc;
using Apps.Common;
using Apps.IBLL;
using Apps.Models.PUB;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Data;
using Apps.Models;
using Wantn.FIS.Enum;
using Apps.IBLL.LMS;
using System.Transactions;
using Apps.IBLL.PL;

namespace Apps.Web.Areas.PUB.Controllers
{
    public class MATERIELController : BaseController
    {
        [Dependency]
        public IPUB_MATERIELBLL m_BLL { get; set; }
        [Dependency]
        public IPUB_MATERIEL_TYPEBLL m_MATERIELBLL { get; set; }


        [Dependency]
        public IPL_RC_DETAILSBLL m_pBLL { get; set; }
        [Dependency]
        public ILMS_TEMPLATE_RELATIONBLL m_trBLL { get; set; }
        [Dependency]
        public ILMS_TEMPLATEBLL m_tBLL { get; set; }
        [Dependency]
        public IPUB_OF_TEMPLATEBLL m_TemplateBLL { get; set; }

        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult Index()
        {
            ViewBag.MetStatisticsType = new SelectList(EnumMvcHelper.GetEnumAllDesc<MetStatisticsType>(), "Key", "Desc");
            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName = "Index")]

        public JsonResult GetList(GridPager pager, string queryStr, string parentId)
        {
                List<PUB_MATERIELModel> list = new List<PUB_MATERIELModel>();
                if (parentId == "0")
                    list = m_BLL.GetPagerList(ref pager, p => (string.IsNullOrEmpty(queryStr) || p.REMARKS.Contains(queryStr) || p.MATERIEL_NAME.Contains(queryStr)), parentId);
                else
                    list = m_BLL.GetPagerList(ref pager, p => (p.MATERIEL_TYPE_ID == parentId)
                               && (string.IsNullOrEmpty(queryStr) || p.REMARKS.Contains(queryStr) || p.MATERIEL_NAME.Contains(queryStr)), parentId);
                GridRows<PUB_MATERIELModel> grs = new GridRows<PUB_MATERIELModel>();
                grs.rows = list;
                grs.total = pager.totalRows;
                return Json(grs);
        }

        #region 物料选择窗口
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetListNotINSupplierId(GridPager pager, string queryStr, string SuppID)
        {
            List<PUB_MATERIELModel> list = m_BLL.GetListNotINSupplierId(ref pager, queryStr, SuppID);
            GridRows<PUB_MATERIELModel> grs = new GridRows<PUB_MATERIELModel>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }

        [SupportFilter(ActionName = "Create")]
        public ActionResult MaterielSel(string SuppID)
        {
            ViewBag.SuppID = SuppID;
            ViewBag.MetStatisticsType = new SelectList(EnumMvcHelper.GetEnumAllDesc<MetStatisticsType>(), "Key", "Desc");
            return View();
        }

        #endregion
        #region 创建
        [SupportFilter]
        public ActionResult Create(string MaterielType)
        {
            ViewBag.MetStatisticsType = new SelectList(EnumMvcHelper.GetEnumAllDesc<MetStatisticsType>(), "Key", "Desc");
            ViewBag.Template = new SelectList(m_TemplateBLL.GetPagerList(ref GridPager.NotPage, p => p.ENABLED == true), "TEMPLATE_ID", "TEMPLATE_NAME");
            ViewBag.MaterielType = new SelectList(m_MATERIELBLL.GetList(p => true), "MATERIEL_TYPE_ID", "MATERIEL_TYPE_NAME"); ;
            //ViewBag.CTemplate =JsonHandler.SerializeObject(m_tBLL.GetList(ref GridPager.NotPage, "").Select(a=>new { Value= a.TEMPLATE_ID,Text=a.TEMPLATE_NAME}).ToList()); //new SelectList(m_tBLL.GetList(ref GridPager.NotPage,""), "TEMPLATE_ID", "TEMPLATE_NAME");
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Create(PUB_MATERIELModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (isRepeated(model))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在相同的物料名称!"));
                }
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (m_BLL.Create(ref errors, model))
                    {
                            LMS_TEMPLATE_RELATION item = new LMS_TEMPLATE_RELATION();
                            item.TEMPLATE_ID = model.CTEMPLATE_ID;
                            item.MINE_MATERIAL_ID = model.MATERIEL_ID;
                            item.UPDATE_TIME = DateTime.Now;
                            item.UPDATE_USER = GetUserId();
                            m_trBLL.Create(ref errors, item);
                        LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + model.TEMPLATE_ID + ",KKSCODE" + model.KKSCODE, "成功", "创建", "PUB_MATERIEL");
                        transactionScope.Complete();
                        return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));

                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + model.TEMPLATE_ID + ",KKSCODE" + model.KKSCODE + "," + errors.Error, "失败", "创建", "PUB_MATERIEL");
                        return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + errors.Error));
                    }
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }
        #endregion

        private bool isRepeated(PUB_MATERIELModel model)
        {
            bool result = false;
            List<PUB_MATERIELModel> oldList = m_BLL.GetList(p => p.MATERIEL_NAME == model.MATERIEL_NAME && p.MATERIEL_ID != model.MATERIEL_ID);
            if (oldList.Count > 0)
            {
                result = true;
            }
            return result;

        }

        #region 修改
        [SupportFilter]
        public ActionResult Edit(string id)
        {
            PUB_MATERIELModel entity = m_BLL.GetById(id);
            ViewBag.MetStatisticsType = new SelectList(EnumMvcHelper.GetEnumAllDesc<MetStatisticsType>(), "Key", "Desc");
            ViewBag.Template = new SelectList(m_TemplateBLL.GetList(ref GridPager.NotPage, ""), "TEMPLATE_ID", "TEMPLATE_NAME");
            //ViewBag.CTemplate = new SelectList(m_tBLL.GetList(ref GridPager.NotPage, ""), "TEMPLATE_ID", "TEMPLATE_NAME",entity.CTEMPLATE_ID);
            ViewBag.MaterielType = new SelectList(m_MATERIELBLL.GetList(p => true), "MATERIEL_TYPE_ID", "MATERIEL_TYPE_NAME"); 
            return View(entity);
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(PUB_MATERIELModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (m_BLL.GetById(model.MATERIEL_ID).MATERIEL_NAME != model.MATERIEL_NAME)
                {
                    if (m_pBLL.GetItem(a => a.MATERIEL_ID == model.MATERIEL_ID) != null)
                    {
                        return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + "该物料已被调运计划使用，禁止修改物料名！"));
                    }
                }
                else
                {
                    if (isRepeated(model))
                    {
                        return Json(JsonHandler.CreateMessage(0, "已存在相同的物料名称!"));
                    }
                }
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (m_BLL.Edit(ref errors, model)|| errors.Error== Resource.NoDataChange)
                    {
                            LMS_TEMPLATE_RELATION item = new LMS_TEMPLATE_RELATION();
                            item.TEMPLATE_ID = model.CTEMPLATE_ID;
                            item.MINE_MATERIAL_ID = model.MATERIEL_ID;
                            item.UPDATE_TIME = DateTime.Now;
                            item.UPDATE_USER = GetUserId();
                            if (m_trBLL.GetById(item.MINE_MATERIAL_ID) == null)
                            {
                                m_trBLL.Create(ref errors, item);
                            }
                            else
                            {
                                m_trBLL.Edit(ref errors, item);
                            }
                        LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + model.TEMPLATE_ID + ",KKSCODE" + model.KKSCODE, "成功", "修改", "PUB_MATERIEL");
                        transactionScope.Complete();
                        return Json(JsonHandler.CreateMessage(1, Resource.UpdateSucceed));

                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        string ErrorCol = errors.Error;
                        LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + model.TEMPLATE_ID + ",KKSCODE" + model.KKSCODE + "," + ErrorCol, "失败", "修改", "PUB_MATERIEL");
                        return Json(JsonHandler.CreateMessage(0, Resource.UpdateFail + errors.Error));
                    }
                }

            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
        }
        #endregion

        #region 详细
        [SupportFilter]
        public ActionResult Details(string id)
        {
            ViewBag.MetStatisticsType = new SelectList(EnumMvcHelper.GetEnumAllDesc<MetStatisticsType>(), "Key", "Desc");
            ViewBag.Template = new SelectList(m_TemplateBLL.GetList(ref GridPager.NotPage, ""), "TEMPLATE_ID", "TEMPLATE_NAME");
            PUB_MATERIELModel entity = m_BLL.GetById(id);
            return View(entity);
        }

        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                if (m_pBLL.GetItem(a => a.MATERIEL_ID == id) != null) return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + "该物料已被调运计划使用，禁止删除！"));
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (m_BLL.Delete(ref errors, id))
                    {
                        m_trBLL.Delete(ref errors, id);
                        LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID:" + id, "成功", "删除", "PUB_MATERIEL");
                        transactionScope.Complete();
                        return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));

                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        string ErrorCol = "该物料已被使用，禁止删除！";
                        LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + id + "," + ErrorCol, "失败", "删除", "PUB_MATERIEL");
                        return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
                    }
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion
        #region 导出导入
        [HttpPost]
        [SupportFilter]
        public ActionResult Import(string filePath)
        {
            var list = new List<PUB_MATERIELModel>();
            bool checkResult = m_BLL.CheckImportData(Utils.GetMapPath(filePath), list, ref errors);
            //校验通过直接保存
            if (checkResult)
            {
                m_BLL.SaveImportData(list);
                LogHandler.WriteServiceLog(GetUserId(), "导入成功", "成功", "导入", "PUB_MATERIEL");
                return Json(JsonHandler.CreateMessage(1, Resource.Import));
            }
            else
            {
                string ErrorCol = errors.Error;
                LogHandler.WriteServiceLog(GetUserId(), ErrorCol, "失败", "导入", "PUB_MATERIEL");
                return Json(JsonHandler.CreateMessage(0, Resource.ImportFail + ErrorCol));
            }
        }
        [HttpPost]
        [SupportFilter(ActionName = "Export")]
        public JsonResult CheckExportData()
        {
            List<PUB_MATERIELModel> list = m_BLL.GetList(ref setNoPagerAscById, "");
            if (list.Count().Equals(0))
            {
                return Json(JsonHandler.CreateMessage(0, "没有可以导出的数据"));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(1, "可以导出"));
            }
        }
        [SupportFilter]
        public ActionResult Export()
        {
            List<PUB_MATERIELModel> list = m_BLL.GetList(ref setNoPagerAscById, "");
            JArray jObjects = new JArray();
            foreach (var item in list)
            {
                var jo = new JObject();
                jo.Add("TEMPLATE_ID", item.TEMPLATE_ID);
                jo.Add("KKSCODE", item.KKSCODE);
                jo.Add("STATISTICS", item.STATISTICS);
                jo.Add("REMARKS", item.REMARKS);
                jo.Add("MATERIEL_TYPE_ID", item.MATERIEL_TYPE_ID);
                jo.Add("MATERIEL_NAME", item.MATERIEL_NAME);
                jo.Add("MATERIEL_ID", item.MATERIEL_ID);
                jObjects.Add(jo);
            }
            var dt = JsonConvert.DeserializeObject<DataTable>(jObjects.ToString());
            var exportFileName = string.Concat(
                "File",
                DateTime.Now.ToString("yyyyMMddHHmmss"),
                ".xlsx");
            return new ExportExcelResult
            {
                SheetName = "Sheet1",
                FileName = exportFileName,
                ExportData = dt
            };
        }
        #endregion
        #region --主表查询--
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetListParent(GridPager pager, string queryStr)
        {
            List<PUB_MATERIEL_TYPEModel> list = m_MATERIELBLL.GetList(ref pager, queryStr);
            GridRows<PUB_MATERIEL_TYPEModel> grs = new GridRows<PUB_MATERIEL_TYPEModel>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }
        #endregion        #region 创建
        [SupportFilter(ActionName = "Create")]
        public ActionResult CreateParent()
        {
            //ViewBag.CTemplate = new SelectList(m_tBLL.GetList(ref GridPager.NotPage, ""), "TEMPLATE_ID", "TEMPLATE_NAME");
            return View();
        }

        [HttpPost]
        [SupportFilter(ActionName = "Create")]
        public JsonResult CreateParent(PUB_MATERIEL_TYPEModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (isRepeatedPar(model))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在类型名为[" + model.MATERIEL_TYPE_NAME + "]的数据!"));
                }


                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (m_MATERIELBLL.Create(ref errors, model))
                    {
                            LMS_TEMPLATE_RELATION item = new LMS_TEMPLATE_RELATION();
                            item.TEMPLATE_ID = model.TEMPLATE_ID;
                            item.MINE_MATERIAL_ID = model.MATERIEL_TYPE_ID;
                            item.UPDATE_TIME = DateTime.Now;
                            item.UPDATE_USER = GetUserId();
                            m_trBLL.Create(ref errors, item);
                            LogHandler.WriteServiceLog(GetUserId(), "REMARKS" + model.REMARKS + ",IS_COAL" + model.IS_COAL, "成功", "创建", "PUB_MATERIEL_TYPE");
                        transactionScope.Complete();
                            return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                       
                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        LogHandler.WriteServiceLog(GetUserId(), "REMARKS" + model.REMARKS + ",IS_COAL" + model.IS_COAL + "," + errors.Error, "失败", "创建", "PUB_MATERIEL_TYPE");
                        return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + errors.Error));
                    }
                }

            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }

        private bool isRepeatedPar(PUB_MATERIEL_TYPEModel model)
        {
            bool result = false;
            List<PUB_MATERIEL_TYPEModel> oldList = m_MATERIELBLL.GetList(p => p.MATERIEL_TYPE_NAME == model.MATERIEL_TYPE_NAME && p.MATERIEL_TYPE_ID != model.MATERIEL_TYPE_ID);
            if (oldList.Count > 0)
            {
                result = true;
            }
            return result;

        }

        #region 修改
        [SupportFilter(ActionName = "Edit")]
        public ActionResult EditParent(string id)
        {
            PUB_MATERIEL_TYPEModel entity = m_MATERIELBLL.GetById(id);
            //ViewBag.CTemplate = new SelectList(m_tBLL.GetList(ref GridPager.NotPage, ""), "TEMPLATE_ID", "TEMPLATE_NAME",entity.TEMPLATE_ID);
            return View(entity);
        }

        [HttpPost]
        [SupportFilter(ActionName = "Edit")]
        public JsonResult EditParent(PUB_MATERIEL_TYPEModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (isRepeatedPar(model))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在类型名为[" + model.MATERIEL_TYPE_NAME + "]的数据!"));
                }

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (m_MATERIELBLL.Edit(ref errors, model)||errors.Error==Resource.NoDataChange )
                    {
                            LMS_TEMPLATE_RELATION item = new LMS_TEMPLATE_RELATION();
                            item.TEMPLATE_ID = model.TEMPLATE_ID;
                            item.MINE_MATERIAL_ID = model.MATERIEL_TYPE_ID;
                            item.UPDATE_TIME = DateTime.Now;
                            item.UPDATE_USER = GetUserId();
                            if (m_trBLL.GetById(item.MINE_MATERIAL_ID) == null)
                            {
                                m_trBLL.Create(ref errors, item);
                            }
                            else
                            {
                                m_trBLL.Edit(ref errors, item);
                            }
                        LogHandler.WriteServiceLog(GetUserId(), "REMARKS" + model.REMARKS + ",IS_COAL" + model.IS_COAL, "成功", "修改", "PUB_MATERIEL");
                        transactionScope.Complete();
                        return Json(JsonHandler.CreateMessage(1, Resource.EditSucceed));

                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        string ErrorCol = errors.Error;
                        LogHandler.WriteServiceLog(GetUserId(), "REMARKS" + model.REMARKS + ",IS_COAL" + model.IS_COAL + "," + ErrorCol, "失败", "修改", "PUB_MATERIEL");
                        return Json(JsonHandler.CreateMessage(0, Resource.EditFail + errors.Error));
                    }
                }

            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
        }
        #endregion

        #region 详细
        [SupportFilter(ActionName = "Details")]
        public ActionResult DetailsParent(string id)
        {
            PUB_MATERIEL_TYPEModel entity = m_MATERIELBLL.GetById(id);
            return View(entity);
        }

        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter(ActionName = "Delete")]
        public ActionResult DeleteParent(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                List<string> mid = m_BLL.GetList(a => a.MATERIEL_TYPE_ID == id).Select(a => a.MATERIEL_ID).ToList();
                if (m_pBLL.GetList(a => true).Select(a => a.MATERIEL_ID).Distinct().ToList().Where(a => mid.Contains(a)).Count() > 0) return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + "该类型中有物料已被调运计划使用，禁止删除！"));
                using (TransactionScope transactionScope = new TransactionScope())
                {

                    bool result1 = m_MATERIELBLL.Delete(ref errors, id);
                    
                    bool result2 = m_BLL.Deletes(ref errors, a => a.MATERIEL_TYPE_ID == id);
                    if (mid.Count <= 0)
                    {
                        //如果子表中没数据，则不执行删除子表
                        result2 = true;
                    }
                        if (result1 && result2)
                    {
                        m_trBLL.Delete(ref errors, id);
                        LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID:" + id, "成功", "删除", "PUB_MATERIEL");
                        transactionScope.Complete();
                        return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));

                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        string ErrorCol = "该物料类型已被使用，删除失败!";
                        LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + id + "," + ErrorCol, "失败", "删除", "PUB_MATERIEL");
                        return Json(JsonHandler.CreateMessage(0, ErrorCol));
                    }
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion

        [HttpPost]
        public JsonResult GetTempList()
        {
            List<SelectListItem> dataList = new List<SelectListItem>();
            return Json(new SelectList(m_tBLL.GetList(ref GridPager.NotPage, ""), "TEMPLATE_ID", "TEMPLATE_NAME"));
        }
    }
}

